<template>
    <div class="compact-container">
        <!-- 标题 + 查询 -->
        <div class="compact-query">
            <span>仓库：</span>
            <el-select v-model="query.warehouse_Code" size="small" class="compact-select" clearable
                @change="changeWarehouse" placeholder="请选择仓库">
                <el-option v-for="w in warehouseOpts" :key="w.warehouse_code" :label="w.warehouse_name"
                    :value="w.warehouse_code" />
            </el-select>

            <span class="compact-label">库区：</span>
            <el-select v-model="query.zone_Code" size="small" class="compact-select" clearable
                :disabled="!query.warehouse_Code" @change="changeZone" placeholder="请选择库区">
                <el-option v-for="z in zoneOpts" :key="z.zone_code" :label="z.zone_name" :value="z.zone_code" />
            </el-select>

            <span class="compact-label">库位：</span>
            <el-select v-model="query.location_Code" size="small" class="compact-select" clearable
                :disabled="!query.zone_Code" placeholder="请选择库位">
                <el-option v-for="l in locationOpts" :key="l.location_code" :label="l.location_name"
                    :value="l.location_code" />
            </el-select>

            <span class="compact-label">产品编码：</span>
            <el-input v-model="query.pro_code" size="small" class="compact-input" clearable @keyup.enter="queryStock" />

            <span class="compact-label">供应商：</span>
            <el-select v-model="query.vendor_Code" size="small" class="compact-select" clearable placeholder="请选择供应商">
                <el-option v-for="v in customerOptonsVender" :key="v.vendor_code" :label="v.vendor_name"
                    :value="v.vendor_code" />
            </el-select>

            <el-button type="primary" size="small" @click="queryStock">查询</el-button>
            <el-button size="small" @click="resetQuery">重置</el-button>
        </div>

        <!-- 表格 -->
        <transition name="fade" mode="out-in">
            <div :key="currentPage"> <!-- 添加包裹元素并设置 key -->
                <el-table :data="tableData" border class="compact-table"
                    :cell-style="{ padding: '4px 0', textAlign: 'center' }"
                    :header-cell-style="{ padding: '6px 0', textAlign: 'center', background: '#f5f7fa', fontWeight: 'bold' }">
                    <el-table-column prop="stock_name" label="货品名称" width="130" fixed />
                    <el-table-column prop="pro_code" label="产品编码" width="130" />
                    <el-table-column prop="pro_brand" label="品牌" width="130" />
                    <el-table-column prop="stock_model" label="规格型号" width="130" />
                    <el-table-column prop="stock_numder" label="库存数量" width="130">
                        <template #default="{ row }">
                            <el-tag :type="row.stock_numder < 10 ? 'danger' : 'success'" size="small">{{
                                row.stock_numder
                                }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="pro_cost_price" label="成本价(元)" width="130">
                        <template #default="{ row }">¥{{ parseFloat(row.pro_cost_price).toFixed(2) }}</template>
                    </el-table-column>
                    <el-table-column prop="pro_sale_price" label="销售价(元)" width="130">
                        <template #default="{ row }">¥{{ parseFloat(row.pro_sale_price).toFixed(2) }}</template>
                    </el-table-column>
                    <el-table-column prop="warehouse_Name" label="仓库" width="103">
                        <template #default="{ row }">
                            {{ warehouseNameMap[row.warehouse_Code] || '加载中...' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="zone_Name" label="库区" width="90">
                        <template #default="{ row }">
                            {{ zoneNameMap[row.zone_Code] || '加载中...' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="location_Name" label="库位" width="90">
                        <template #default="{ row }">
                            {{ locationNameMap[`${row.zone_Code}_${row.location_Code}`] || '加载中...' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="vendor_Name" label="供应商" width="140" />
                </el-table>

                <!-- 分页 -->
                <div class="compact-pagination">
                    <el-pagination size="small" background layout="total, sizes, prev, pager, next, jumper"
                        :current-page="currentPage" :page-size="pageSize" :total="pageCount"
                        :page-sizes="[5, 10, 20, 30]" @size-change="handleSizeChange"
                        @current-change="handleCurrentChange" />
                </div>
            </div>
        </transition>
    </div>



</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { Search } from '@element-plus/icons-vue'



// 查询条件
const query = ref({
    warehouse_Code: '',
    zone_Code: '',
    location_Code: '',
    pro_code: '',
    vendor_Code: ''
})

const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const pageCount = ref(0)
// const loading = ref(false)


const warehouseOpts = ref([])   // 仓库下拉
const zoneOpts = ref([])    // 库区下拉
const locationOpts = ref([])    // 库位下拉

// 格式化货币显示
const formatCurrency = (value) => {
    return '¥' + parseFloat(value).toFixed(2)
}
const warehouseNameMap = ref({})
const zoneNameMap = ref({})
const locationNameMap = ref({})

function fetchData() {
    //loading.value = true

    axios.get('http://localhost:5181/api/Inv_Stock/Get_Select_stock', {
        params: {
            weahouse_code: query.value.warehouse_Code,
            zone_code: query.value.zone_Code,
            location_code: query.value.location_Code,
            Vendor_Code: query.value.vendor_Code,
            pro_code: query.value.pro_code,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: { Authorization: localStorage.getItem('token') }
    }).then(async res => {
        tableData.value = res.data
        var warehouse_code=ref('');
        // 仓库名称缓存
        const uniqueWarehouseCodes = [...new Set(res.data.map(r => r.warehouse_Code).filter(Boolean))]
        for (const code of uniqueWarehouseCodes) {
            if (!warehouseNameMap.value[code]) {
                const res = await axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBy_Select_Async_code", {
                    params: { warehouse_code: code },
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                })
                warehouseNameMap.value[code] = res.data?.[0]?.warehouse_name || '未知仓库'
            }
        }

        // 库区名称缓存
        const uniqueZoneCodes = [...new Set(res.data.map(r => r.zone_Code).filter(Boolean))]
        for (const code of uniqueZoneCodes) {
            if (!zoneNameMap.value[code]) {
                const warehouseCode = res.data.find(r => r.zone_Code === code)?.warehouse_Code
                if (!warehouseCode) {
                    zoneNameMap.value[code] = '未知库区'
                    continue
                }

                const zoneRes = await axios.get(
                    "http://localhost:5181/api/Db_warehouse_zone/Warehouse_zone_By_Select_Async_code",
                    {
                        params: {
                            warehouse_code: warehouseCode,
                            zone_code: code
                        },
                        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                    }
                )
                zoneNameMap.value[code] = zoneRes.data?.[0]?.zone_name || '未知库区'
            }
        }

        // 库位名称缓存（需要 zone_code + location_code）
        const uniqueLocationKeys = [
            ...new Set(
                res.data
                    .filter(r => r.zone_Code && r.location_Code)
                    .map(r => `${r.zone_Code}_${r.location_Code}`)
            )
        ]

        for (const key of uniqueLocationKeys) {
            if (!locationNameMap.value[key]) {
                const [zone_code, location_code] = key.split('_')
                const res = await axios.get(
                    "http://localhost:5181/api/Db_warehouse_location/Warehouse_location_By_Select_Async_code",
                    {
                        params: { zone_code, location_code },
                        headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                    }
                )
                locationNameMap.value[key] = res.data?.[0]?.location_name || '未知库位'
            }
        }

        //loading.value = false
    }).catch(() => {
        loading.value = false
    })
}




// 获取总数
function fetchCount() {
    axios.get('http://localhost:5181/api/Inv_Stock/Get_Select_stock_count', {
        params: {
            weahouse_code: query.value.warehouse_Code,   // ← 首字母小写
            zone_code: query.value.zone_Code,
            location_code: query.value.location_Code,
            Vendor_Code: query.value.vendor_Code,
            pro_code: query.value.pro_code,
            pro_code: query.pro_code,
        },
        headers: { Authorization: localStorage.getItem('token') }
    }).then(res => (pageCount.value = res.data))
}

// 查询按钮
function queryStock() {
  
    fetchCount()
    fetchData()
}

// 重置按钮
function resetQuery() {
    query.value = {
        warehouse_Code: '',
        zone_Code: '',
        location_Code: '',
        pro_code: '',
        vendor_Code: ''
    }
    //currentPage.value = 1          // ← 重置到第一页
    queryStock()
}


// 获取仓库下拉
function getWarehouseSelect() {
    return axios.get('http://localhost:5181/api/Db_warehouse/WarehouseBySelect', {
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
        warehouseOpts.value = res.data
    })
}

// 根据仓库编码获取库区下拉
function getZoneByWarehouse(warehouseCode) {
    if (!warehouseCode) return
    return axios.get('http://localhost:5181/api/Db_warehouse_zone/warehouse_zone', {
        params: { warehouse_code: warehouseCode },
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
        zoneOpts.value = res.data
        // 切换仓库时清空库位
        locationOpts.value = []
    })
}

// 根据库区编码获取库位下拉
function getLocationByZone(zoneCode) {
    if (!zoneCode) return
    return axios.get('http://localhost:5181/api/Db_warehouse_location/warehouse_location', {
        params: { zone_code: zoneCode },
        headers: { Authorization: `Bearer ${localStorage.getItem('token')}` }
    }).then(res => {
        locationOpts.value = res.data
    })
}
const customer_name = ref("")

const customerOptonsVender = ref([])//供应商信息
//查询供应商
function getCustomerVender() {
    axios.get("http://localhost:5181/api/Values/Pinv_VendorWhere", {
        params: {
            Vendor_name: customer_name.value
        }, headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
        }
    }).then((result) => {
        customerOptonsVender.value = result.data
    }).catch((err) => {
        console.info(err)
    });
}

// 仓库变化 → 联动库区
function changeWarehouse(code) {
    query.zone_Code = ''
    query.location_Code = ''
    getZoneByWarehouse(code)
}

// 库区变化 → 联动库位
function changeZone(code) {
    query.location_Code = ''
    getLocationByZone(code)
}


// 分页
function handleSizeChange(val) {
    pageSize.value = val
    fetchData()
}
function handleCurrentChange(val) {
    currentPage.value = val
    fetchData()
}

onMounted(() => {
    fetchCount()
    fetchData()
    getWarehouseSelect()
    getCustomerVender()
})
</script>

<style scoped lang="scss">
.compact-container {
    padding: 12px;
    
}

.compact-query {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 12px;
    margin-top: -30px
}

.compact-input {
    width: 160px !important
}

.compact-label {
    margin-left: 8px
}

.compact-select {
    width: 140px
}

.compact-add-btn {
    margin-left: auto
}

.compact-table {
    font-size: 12px
}

.compact-table :deep(.el-table__cell) {
    padding: 4px 0
}

.compact-table :deep(.el-tag) {
    padding: 0 6px;
    height: 22px;
    line-height: 22px;
    font-size: 12px
}

.compact-pagination {
    margin-top: 12px;
    display: flex;
    justify-content: center
}
.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>